package com.own.business.push.persistence.mysql.method;

import com.own.business.push.core.base.BaseSaveRegistrationIdMethod;
import com.own.business.push.core.model.RegisterRegistrationIdModel;
import com.own.business.push.persistence.mysql.service.PushRegistrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * PersistenceMysqlSaveRegistrationIdMethod
 *
 * @author chenxueli
 * @date 2023-11-16 14:19:00
 */
@Slf4j
@Component
public class PersistenceMysqlSaveRegistrationIdMethod implements BaseSaveRegistrationIdMethod {

    @Resource
    private PushRegistrationService pushRegistrationService;

    /**
     * 保存注册id
     *
     * @param model 注册id模型
     */
    @Override
    public void save(RegisterRegistrationIdModel model) {
        // 查询是否有相同的userId注册或者注册id存在，如果存在直接删除原来的信息
        pushRegistrationService.deleteByUserId(model.getUserId());
        pushRegistrationService.deleteByRegId(model.getRegistrationId(), model.getModule());
        // 添加信息新的信息
        pushRegistrationService.save(model.getUserId(), model.getRegistrationId(), model.getModule());
    }

    /**
     * 根据用户id删除
     *
     * @param userId 用户id
     */
    @Override
    public void removeByUserId(Long userId) {
        pushRegistrationService.deleteByUserId(userId);
    }

    /**
     * 根据用户id获取注册id
     *
     * @param userId 用户id
     * @return 注册id
     */
    @Override
    public RegisterRegistrationIdModel getByUserId(Long userId) {
        var po = pushRegistrationService.getByUserId(userId);
        if (po != null) {
            return new RegisterRegistrationIdModel()
                    .setUserId(po.getFkUserId())
                    .setRegistrationId(po.getRegId())
                    .setModule(po.getModule());
        }
        return null;
    }

    /**
     * 根据用户id列表获取注册id列表
     *
     * @param userIdList 用户id列表
     * @return 注册id列表
     */
    @Override
    public List<RegisterRegistrationIdModel> listByUserIdList(Collection<Long> userIdList) {
        var poList = pushRegistrationService.listByUserIdList(userIdList);
        return poList.stream().map(po ->
                        new RegisterRegistrationIdModel()
                                .setUserId(po.getFkUserId())
                                .setRegistrationId(po.getRegId())
                                .setModule(po.getModule())
                )
                .collect(Collectors.toList());
    }

    /**
     * 根据模块查询注册id列表
     *
     * @param module 模块
     * @return 注册id列表
     */
    @Override
    public List<String> listRegIdListByModule(String module) {
        return pushRegistrationService.listRegIdListByModule(module);
    }

}
